<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /**
       * 实现一个组合compose的方法，使其可以正确调用每个中间件
       *
       * 规定中间件写法：
       * function(val, next) {
       *    // 前置操作
       *    next(val + 1); // 触发下一个中间件
       *    // 后续操作
       * }
       */

      function compose(...middlewares) {
        return function loop(input) {
          const dispatch = (x, index) => {
            if (index >= middlewares.length) return;
            const fn = middlewares[index];
            //第二个参数就是next next主要执行下一次的函数
            fn(x, (x) => {
              dispatch(x, index + 1);
            });
          };

          dispatch(input, input);
        };
      }

      function add1(x, next) {
        console.log("add1 before");
        next(x + 1);
        console.log("add1 after");
      }

      function add2(x, next) {
        console.log("add2 before");
        next(x + 2);
        console.log("add2 after");
      }

      function output(x) {
        console.log("output:", x);
      }

      const input = 0;
      compose(add1, add2, (output) => {
        console.log("output:", output);
      })(input);

      /**
       * 输出:
       *
       * add1 before
       * add2 before
       * output: 3
       * add2 after
       * add1 after
       */
    </script>
  </body>
</html>
